import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import {
  getAllBranches,
  getDefaultBranch,
  getProtectedBranchesList,
  postDefaultBranch,
  deleteProtectedBranch,
  updateProtectedBranch,
  addProtectedBranch,
  getProjectServices,
} from 'api';
import intl from '../../../../../../../../../locale';

const ns = NameSpace('PROJECT_SETTINGS_BRANCHES');
export const UPDATE_DATA = ns('UPDATE_DATA');

const { pathResource } = window.FORCE;

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

// 获取扫描设置
export function getServices() {
  return (dispatch) => {
    updateData({
      isLoadingServices: true,
    })(dispatch);
    getProjectServices()
      .then((result) => {
        updateData({
          integration_service_setting: result.integration_service_setting || {},
          isLoadingServices: false,
        })(dispatch);
      })
      .catch((err) => {
        updateData({
          isLoadingServices: false,
        })(dispatch);
        console.error(err);
      });
  };
}

export function getProtectedBranches() {
  return (dispatch) => {
    updateData({
      isLoadingTable: true,
    })(dispatch);
    getProtectedBranchesList()
      .then((result) => {
        updateData({
          protectedBranches: result.slice(1) || [],
          isLoadingTable: false,
        })(dispatch);
      })
      .catch(() => {
        updateData({
          isLoadingTable: false,
        })(dispatch);
      });
  };
}

export function getBaseFormInfo() {
  return (dispatch) => {
    Promise.all([getAllBranches(), getDefaultBranch()])
      .then((results) => {
        const allBranches = results[0] ? results[0].slice(1) : [];
        const defaultBranch = results[1] ? results[1].default_branch : '';
        updateData({
          allBranches,
          defaultBranch,
          // 保存返回的默认分支
          curDefaultBranch: defaultBranch,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}

export function setDefaultBranch(value, callback) {
  return (dispatch) => {
    callback({
      submitting: true,
    });

    postDefaultBranch(value)
      .then((result) => {
        updateData({
          defaultBranch: result.default_branch || '',
          curDefaultBranch: result.default_branch || '',
        })(dispatch);
        callback({
          submitting: false,
          isModalOpen: false,
        });
        window.FORCE.pathResource.defaultBranch = result.default_branch || '';

        Message.success({
          title: intl.get({
            id: 'code-assets.settingsBranches.actions.TheDefaultBranchIsUpdated',
            defaultMessage: '默认分支更新成功',
          }),
        });
      })
      .catch(() => {
        callback({
          submitting: false,
          isModalOpen: false,
        });

        Message.error({
          title: intl.get({
            id: 'code-assets.settingsBranches.actions.FailedToUpdateTheDefault',
            defaultMessage: '默认分支更新失败',
          }),
        });
      });
  };
}

export function addRecord() {
  return (dispatch, getState) => {
    updateData({
      isUpdatingRecord: true,
    })(dispatch);
    const state = getState().project.projectSettings.settingsBranches;
    const { record, modalType } = state;
    const newDefault_assignees =
      record.merge_request && record.merge_request.default_assignees
        ? record.merge_request.default_assignees.map((item) => {
            return item._userId;
          })
        : [];
    const newMerge_request = record.merge_request
      ? { ...record.merge_request, default_assignees: newDefault_assignees }
      : { default_assignees: newDefault_assignees };
    const newRecord = {
      ...record,
      merge_request: newMerge_request,
      allow_push_user_ids: record?.allow_push_users?.map((va) => va.id),
      allow_merge_user_ids: record?.allow_merge_users?.map((va) => va.id),
    };
    const promise =
      modalType === 'edit' ? updateProtectedBranch(newRecord) : addProtectedBranch(newRecord);
    promise
      .then(() => {
        Message.success({
          title:
            modalType === 'edit'
              ? intl.get({
                  id: 'code-assets.settingsBranches.actions.TheProtectionBranchRuleIs',
                  defaultMessage: '保护分支规则更新成功',
                })
              : intl.get({
                  id: 'code-assets.settingsBranches.actions.TheProtectionBranchRuleIs.1',
                  defaultMessage: '保护分支规则新建成功',
                }),
        });

        updateData({
          isUpdatingRecord: false,
          isModalOpen: false,
        })(dispatch);
        getProtectedBranches()(dispatch);
      })
      .catch(() => {
        updateData({
          isUpdatingRecord: false,
        })(dispatch);
        // Message.error({
        //   title: modalType === 'edit' ? '修改失败' : '添加失败',
        // });
      });
  };
}

// export function setProtectedBranches(data) {
//   return (dispatch) => {
//     exceed
//       .forceFetch({
//         api: 'project.protected_branch.set',
//         params: {
//           projectId: pathResource.id,
//           branchName: data.protected_branch,
//         },
//         data: {
//           developers_can_push: data.developers_can_push,
//           developers_can_accept: data.developers_can_accept,
//           developers_can_merge: data.developers_can_merge,
//         },
//       })
//       .then(() => {
//         Message.success({
//           title: '成功',
//         });
//         getProtectedBranches()(dispatch);
//       });
//   };
// }

export function unprotectedBranch(record, cb) {
  return (dispatch) => {
    deleteProtectedBranch({ id: record.id })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.settingsBranches.actions.TheProtectedBranchIsDeleted',
            defaultMessage: '保护分支删除成功',
          }),
        });

        getProtectedBranches()(dispatch);
        cb && cb();
      })
      .catch(() => {
        Message.error({
          title: intl.get({
            id: 'code-assets.settingsBranches.actions.FailedToDeleteTheProtected',
            defaultMessage: '保护分支删除失败',
          }),
        });

        cb && cb();
      });
  };
}

export function getCodeReviewSetting() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'codereview.setting.get',
        params: {
          id: pathResource.id,
        },
      })
      .then((result) => {
        updateData({
          codereviewSetting: result,
        })(dispatch);
      });
  };
}

// export function updateCodeReviewSetting({ default_reviewers, default_subscribers, test_names }) {
//   return (dispatch, getState) => {
//     const state = getState().project.projectSettings.settingsBranches;
//     const { codereviewSetting } = state;
//     exceed
//       .forceFetch({
//         api: 'codereview.setting.update',
//         params: {
//           id: pathResource.id,
//         },
//         data: {
//           allow_self_approval: codereviewSetting.allow_self_approval,
//           minimun_approval: codereviewSetting.minimun_approval,
//           require_code_owner_check: codereviewSetting.require_code_owner_check,
//           enable_code_owner_focus_mode: codereviewSetting.enable_code_owner_focus_mode,
//           require_discussion_processed: codereviewSetting.require_discussion_processed,
//           reset_approval_when_new_push: codereviewSetting.reset_approval_when_new_push,
//           default_reviewers,
//           default_subscribers,
//           test_names,
//         },
//       })
//       .then(() => {
//         Message.success({
//           title: '成功',
//         });
//         // TODO 此处应该刷新表格
//       });
//   };
// }

export function getTestName() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'codereview.setting.getTestName',
        params: {
          id: pathResource.id,
        },
      })
      .then((result) => {
        updateData({
          testName: result.tests,
        })(dispatch);
      });
  };
}

export function getStandardInlineCheck() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.mr.standard_inline_check',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        updateData({
          standard_inline_check: result.list,
        })(dispatch);
      });
  };
}

// export function putStandardInlineCheck({ id, enable }) {
//   return () => {
//     exceed
//       .forceFetch({
//         api: 'project.mr.standard_inline_check.put',
//         params: {
//           projectId: pathResource.id,
//           standardInlineCheckId: id,
//         },
//         data: { enable },
//       })
//       .then(() => {
//         Message.success({
//           title: '操作成功',
//         });
//       });
//   };
// }

export function getFlowBuildNames() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'projects.builds.flow',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        updateData({
          flowBuildNames: result.list,
        })(dispatch);
      });
  };
}
